package znet

import (
	"fmt"
	"io"
	"log/slog"
	"net"
	"zinx/ziface"
)

type Connection struct {
	// 当前TCP链接对象
	conn *net.TCPConn
	// 当前链接的ID
	connID uint32
	// 链接的状态 是否关闭
	isClosed bool
	// 处理业务的方法
	handleAPI ziface.HandleFunc
	//  接收断开链接的通知
	ExitChan chan struct{}
}

func NewConnection(conn *net.TCPConn, connID uint32, handleAPI ziface.HandleFunc) *Connection {
	c := &Connection{
		conn:      conn,
		connID:    connID,
		isClosed:  false,
		handleAPI: handleAPI,
		ExitChan:  make(chan struct{}, 1),
	}
	return c
}
func (c *Connection) Start() {
	slog.Info(fmt.Sprint("Conn Start().. ConnID = ", c.connID))
	// 启动读数据的业务
	go c.startRead()
	// 启动写数据的业务
}
func (c *Connection) startRead() {
	slog.Info("Reader Goroutine is running...")
	defer func() {
		c.Stop()
	}()
	for {
		// 读取数据到buf中，最大512字节
		buf := make([]byte, 512)
		num, err := c.conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				return
			}
			slog.Error("Recv Buf Err", err)
			continue
		}
		// 调用当前链接所绑定的HandleAPI
		err = c.handleAPI(c.conn, buf, num)
		if err != nil {
			slog.Error(fmt.Sprint("ConnID", c.connID, "Handle Is Error", err))
			break
		}
	}
}
func (c *Connection) writeRead() {

}
func (c *Connection) Stop() {
	if c.isClosed {
		// 关闭
		return
	}
	if err := c.conn.Close(); err != nil {
		slog.Error(fmt.Sprint("Conn Disconnect Error", err))
		return
	}
	// 修改为断开连接状态
	c.isClosed = true
	// 关闭管道
	close(c.ExitChan)
	slog.Info(fmt.Sprint("Conn Stop().. ConnID = ", c.connID))
}

func (c *Connection) Send(bytes []byte) error {
	//TODO implement me
	panic("implement me")
}

func (c *Connection) GetTCPConnection() *net.TCPConn {
	return c.conn
}
func (c *Connection) GetConnId() uint32 {
	return c.connID
}

func (c *Connection) RemoteAddr() net.Addr {
	return c.conn.RemoteAddr()
}
